// src/models/category.model.js
import { DataTypes } from "sequelize";
import { sequelize } from "../config/sequelize.js";
import { NotFoundError, BadRequestError } from "../utils/errors.js";

// 分类模型定义

export default (sequelize)=> {
  const Category = sequelize.define(
    "Categories",
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      name: {
        type: DataTypes.STRING(50),
        allowNull: false,
        validate: {
          notEmpty: {
            msg: "分类名称不能为空",
          },
          len: {
            args: [2, 50],
            msg: "分类名称长度必须在2-50个字符之间",
          },
        },
      },
      slug: {
        type: DataTypes.STRING(60),
        allowNull: true,
        unique: true,
        validate: {
          is: {
            args: /^[a-z0-9-]+$/,
            msg: "URL标识只能包含小写字母、数字和连字符",
          },
        },
      },
      parentId: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: {
          model: "Categories",
          key: "id",
        },
      },
      level: {
        type: DataTypes.INTEGER,
        defaultValue: 1,
        validate: {
          min: 1,
          max: 3,
        },
      },
      sortOrder: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
      },
      image: {
        type: DataTypes.STRING,
        validate: {
          isUrl: {
            msg: "图片地址必须是有效的URL",
          },
        },
      },
      isVisible: {
        type: DataTypes.BOOLEAN,
        defaultValue: true,
      },
      metaTitle: {
        type: DataTypes.STRING(100),
      },
      metaDescription: {
        type: DataTypes.STRING(200),
      },
    },
    {
      tableName: "categories",
      timestamps: true,
      paranoid: true, // 启用软删除
      defaultScope: {
        where: { isVisible: true },
      },
      scopes: {
        withHidden: {
          where: {},
        },
        tree: {
          attributes: ["id", "name", "parentId", "level", "sortOrder"],
        },
      },
    }
  );

  // 定义关联关系（延迟执行）
  Category.associate = (models) => {
    Category.hasMany(models.Category, {
      as: "children",
      foreignKey: "parentId",
      onDelete: "CASCADE",
    });
    Category.belongsTo(models.Category, {
      as: "parent",
      foreignKey: "parentId",
    });
    // 新增与商品的关联
    Category.hasMany(models.Product, {
      as: "products",
      foreignKey: "category_id",
    });
  };

  // 类方法：获取分类树（递归）
  Category.getTree = async function () {
    const roots = await this.findAll({
      where: { parentId: null },
      include: [
        {
          model: Category,
          as: "children",
          include: [
            {
              model: Category,
              as: "children",
            },
          ],
        },
      ],
      order: [["sortOrder", "ASC"]],
    });

    return roots;
  };

  // 类方法：验证分类是否存在
  Category.validateExists = async function (id) {
    const category = await this.findByPk(id);
    if (!category) {
      throw new NotFoundError("商品分类不存在");
    }
    return category;
  };

  // 类方法：检查分类名称是否唯一
  Category.checkNameUnique = async function (name, excludeId = null) {
    const where = { name };
    if (excludeId) {
      where.id = { [sequelize.Op.ne]: excludeId };
    }

    const exists = await this.findOne({ where });
    if (exists) {
      throw new BadRequestError("分类名称已存在");
    }
  };

  // 类方法：检查是否可以删除分类
  Category.checkCanDelete = async function (id) {
    const hasChildren = await this.count({
      where: { parentId: id },
    });

    if (hasChildren > 0) {
      throw new BadRequestError("请先删除子分类");
    }

    // 检查是否有商品关联
    const hasProducts = await sequelize.models.Product.count({
      where: { category_id: id },
    });

    if (hasProducts > 0) {
      throw new BadRequestError("分类下存在商品，无法删除");
    }
  };

  return Category;
}
